//
//  ClassViewController.m
//  NewProject
//
//  Created by Livespro on 2016/11/26.
//  Copyright © 2016年 FZ. All rights reserved.
//

#import "ClassViewController.h"

#import "CommonWebViewController.h"

#define kClassContents @[@"延时拍照",@"拍照"]

#define angelToRandian(x)  ((x)/180.0*M_PI)

@interface ClassViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong)  UICollectionView *collectionList;

@property (nonatomic, strong)  NSMutableArray *dataArray;

@property (nonatomic, strong)  UIView *snapshotView; //截屏得到的view
@property (nonatomic, strong)  NSIndexPath *indexPath;
@property (nonatomic, strong)  NSIndexPath *nextIndexPath;
@property (nonatomic,   weak)  UICollectionViewCell *originalCell;

@end

@implementation ClassViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
}

- (void)staticViewsWithoutNib{
    
    _dataArray = [NSMutableArray arrayWithArray:kClassContents];
    
    [self.view addSubview:self.collectionList];
}

- (UICollectionView *)collectionList{
    
    if (!_collectionList) {
        
        //layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.itemSize = CGSizeMake((kScreenWidth - 6*10)/5 , (kScreenWidth - 6*10)/5 );
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);

        _collectionList = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - 44) collectionViewLayout:layout];
        _collectionList.backgroundColor = pageColor;
        _collectionList.delegate = self;
        _collectionList.dataSource = self;
        //注册cell
        [_collectionList registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class])];
    }
    return _collectionList;
}

#pragma mark - collection Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;{
    

    return _dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class]) forIndexPath:indexPath];
    
    UILongPressGestureRecognizer *longPress = [cell gestureRecognizers].firstObject;
    
    if (!longPress) {
        
        //给每个cell添加一个长按手势
        longPress =[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
        
        [cell addGestureRecognizer:longPress];
    }
    
    UILabel *tip_label = [cell.contentView viewWithTag:1001];
    
    if (!tip_label) {
        
        tip_label = [UILabel labelWithText:nil TextFont:12 TextColor:Colorfff Frame:CGRectMake(0, 0,CGRectGetWidth(cell.contentView.frame), CGRectGetHeight(cell.contentView.frame)) NumberOfLines:1 TextAlignment:NSTextAlignmentCenter BackgroundColor:[UIColor clearColor]];
        tip_label.tag = 1001;
        
        [cell.contentView addSubview:tip_label];
    }
    
    tip_label.text = _dataArray[indexPath.item];
    
    cell.contentView.backgroundColor = [UIColor colorWithHexString:@"000000" alpha:.6f];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;{
    
//    [[MobManager manager] showShareActionSheetWithUrlString:@"http://open.qq.com" title:@"分享" images:@[] content:@"分享测试"];
//    [[MobManager manager] loginWithPlatform:SSDKPlatformTypeQQ Result:^(BOOL isSuccess, SSDKUser *user) {
//
//        NSLog(@"%@",user);
//    }];
    
    [[LXRouter shareRouter] routeMap:@"mine://TVC.push" RouteBlock:nil animated:NO completion:nil];
    
//    CommonWebViewController *vc = [[CommonWebViewController alloc] init];
//    
//    vc.urlString = @"http://baidu.com";
//    
//    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - MovingAction
- (void)longPressAction:(UILongPressGestureRecognizer *)longPress{
    
    //记录上一次手势的位置
    static CGPoint startPoint;
    //触发长按手势的cell
    UICollectionViewCell * cell = (UICollectionViewCell *)longPress.view;
    
    //开始长按
    if (longPress.state == UIGestureRecognizerStateBegan) {
        
        [self shakeAllCell];
        //获取cell的截图
        _snapshotView  = [cell snapshotViewAfterScreenUpdates:YES];
        _snapshotView.center = cell.center;
        [_collectionList addSubview:_snapshotView];
        _indexPath= [_collectionList indexPathForCell:cell];
        _originalCell = cell;
        _originalCell.hidden = YES;
        startPoint = [longPress locationInView:_collectionList];
        
        //移动
    }else if (longPress.state == UIGestureRecognizerStateChanged){
        
        CGFloat tranX = [longPress locationOfTouch:0 inView:_collectionList].x - startPoint.x;
        CGFloat tranY = [longPress locationOfTouch:0 inView:_collectionList].y - startPoint.y;
        
        //设置截图视图位置
        _snapshotView.center = CGPointApplyAffineTransform(_snapshotView.center, CGAffineTransformMakeTranslation(tranX, tranY));
        startPoint = [longPress locationOfTouch:0 inView:_collectionList];
        //计算截图视图和哪个cell相交
        for (UICollectionViewCell *cell in [_collectionList visibleCells]) {
            //跳过隐藏的cell
            if ([_collectionList indexPathForCell:cell] == _indexPath) {
                
                continue;
            }
            //计算中心距
            CGFloat space = sqrtf(pow(_snapshotView.center.x - cell.center.x, 2) + powf(_snapshotView.center.y - cell.center.y, 2));
            
            //如果相交一半且两个视图Y的绝对值小于高度的一半就移动
            if (space <= _snapshotView.bounds.size.width * 0.5 && (fabs(_snapshotView.center.y - cell.center.y) <= _snapshotView.bounds.size.height * 0.5)) {
                _nextIndexPath = [_collectionList indexPathForCell:cell];
                if (_nextIndexPath.item > _indexPath.item) {
                    for (NSUInteger i = _indexPath.item; i < _nextIndexPath.item ; i ++) {
                        [self.dataArray exchangeObjectAtIndex:i withObjectAtIndex:i + 1];
                    }
                }else{
                    for (NSUInteger i = _indexPath.item; i > _nextIndexPath.item ; i --) {
                        [self.dataArray exchangeObjectAtIndex:i withObjectAtIndex:i - 1];
                    }
                }
                //移动
                [_collectionList moveItemAtIndexPath:_indexPath toIndexPath:_nextIndexPath];
                //设置移动后的起始indexPath
                _indexPath = _nextIndexPath;
                break;
            }
        }
        
        //停止
    }else if(longPress.state == UIGestureRecognizerStateEnded){
        
        [self stopShake];
        [_snapshotView removeFromSuperview];
        _originalCell.hidden = NO;
    }
}

#pragma mark - 开始/停止 抖动动画
- (void)shakeAllCell{
    
    CAKeyframeAnimation* anim = [CAKeyframeAnimation animation];
    anim.keyPath = @"transform.rotation";
    anim.values = @[@(angelToRandian(-5)),@(angelToRandian(5)),@(angelToRandian(-5))];
    anim.repeatCount = MAXFLOAT;
    anim.duration = 0.3;
    NSArray *cells = [self.collectionList visibleCells];
    for (UICollectionViewCell *cell in cells) {
        /**如果加了shake动画就不用再加了*/
        if (![cell.layer animationForKey:@"shake"]) {
            [cell.layer addAnimation:anim forKey:@"shake"];
        }
    }
}

- (void)stopShake{
    
    NSArray *cells = [self.collectionList visibleCells];
    for (UICollectionViewCell *cell in cells) {
        [cell.layer removeAllAnimations];
    }
}

@end
